/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.IdentityOrder;
import me.zhengjie.modules.system.repository.IdentityOrderRepository;
import me.zhengjie.modules.system.service.IdentityOrderService;
import me.zhengjie.modules.system.service.dto.IdentityOrderDto;
import me.zhengjie.modules.system.service.dto.IdentityOrderQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.IdentityOrderMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author 王宇
* @date 2023-10-07
**/
@Service
@RequiredArgsConstructor
public class IdentityOrderServiceImpl implements IdentityOrderService {

    private final IdentityOrderRepository identityOrderRepository;
    private final IdentityOrderMapper identityOrderMapper;

    @Override
    public Map<String,Object> queryAll(IdentityOrderQueryCriteria criteria, Pageable pageable){
        Page<IdentityOrder> page = identityOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(identityOrderMapper::toDto));
    }

    @Override
    public List<IdentityOrderDto> queryAll(IdentityOrderQueryCriteria criteria){
        return identityOrderMapper.toDto(identityOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public IdentityOrderDto findById(Long orderId) {
        IdentityOrder identityOrder = identityOrderRepository.findById(orderId).orElseGet(IdentityOrder::new);
        ValidationUtil.isNull(identityOrder.getOrderId(),"IdentityOrder","orderId",orderId);
        return identityOrderMapper.toDto(identityOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IdentityOrderDto create(IdentityOrder resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setOrderId(snowflake.nextId()); 
        return identityOrderMapper.toDto(identityOrderRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(IdentityOrder resources) {
        IdentityOrder identityOrder = identityOrderRepository.findById(resources.getOrderId()).orElseGet(IdentityOrder::new);
        ValidationUtil.isNull( identityOrder.getOrderId(),"IdentityOrder","id",resources.getOrderId());
        identityOrder.copy(resources);
        identityOrderRepository.save(identityOrder);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long orderId : ids) {
            identityOrderRepository.deleteById(orderId);
        }
    }

    @Override
    public void download(List<IdentityOrderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (IdentityOrderDto identityOrder : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("订单编号", identityOrder.getOrderNo());
            map.put("openid", identityOrder.getOpenId());
            map.put("预支付流水号", identityOrder.getPrePayid());
            map.put("支付流水号", identityOrder.getPaySerialid());
            map.put("支付金额", identityOrder.getPayAmount());
            map.put("身份金额", identityOrder.getIdentityAmount());
            map.put("优惠金额", identityOrder.getDiscountAmount());
            map.put("支付状态，0：未支付，1：已支付", identityOrder.getPayStatus());
            map.put("更新时间", identityOrder.getUpdateTime());
            map.put("创建时间", identityOrder.getCreateTime());
            map.put("备注", identityOrder.getRemark());
            map.put("类型", identityOrder.getOrderType());
            map.put("业务ID", identityOrder.getBizId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public IdentityOrder findOne(String orderSn) {
        IdentityOrderQueryCriteria criteria = new IdentityOrderQueryCriteria();
        criteria.setOrderNo(orderSn);
        List<IdentityOrder> all = identityOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        if (CollectionUtils.isEmpty(all)){
            return null;
        }
        return all.get(0);
    }
}